package com.sky.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.socketsereve.WebSocketServer;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 订单
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    // 商家地址
    @Value("${sky.shop.address}")
    private String shopAddress;
    // 百度地图的ak
    @Value("${sky.baidu.ak}")
    private String ak;
    // 百度地图获取经纬度的url
    private static final String BAIDU_GEOCODING_URL = "https://api.map.baidu.com/geocoding/v3";
    // 百度地图获取路线规划的url
    private static final String BAIDU_DIRECTIONLITE_URL = "https://api.map.baidu.com/directionlite/v1/driving";

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer websocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 异常情况的处理（收货地址为空、购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 获取用户地址,判断是否在配送范围内
        String userAddress = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        checkOutOfRange(userAddress);

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        // 查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectByShoppingCart(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        // 向订单表插入1条数据
        orderMapper.insert(order);

        // 订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }

        // 向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        // 清理购物车中的数据
        shoppingCartMapper.deleteByUserId(userId);

        // 封装返回结果
        return OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        // 修改订单状态
        orderMapper.update(orders);

        // 发送消息，提醒商家有新的订单
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1); // 1-来单提醒
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号" + ordersDB.getNumber());
        String message = JSON.toJSONString(map);
        websocketServer.sendToAllClient(message);
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 判断分页参数
        if (ordersPageQueryDTO.getPage() == 0){
            ordersPageQueryDTO.setPage(1);
        }
        if (ordersPageQueryDTO.getPageSize() == 0){
            ordersPageQueryDTO.setPageSize(10);
        }

        // 分页查询订单
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();
        // 判断是否获取到数据
        if (page != null && page.getTotal() > 0) {
            // 获取到数据,根据订单id查询具体订单信息
            List<Orders> ordersList = page.getResult();
            for (Orders o : ordersList) {
                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(o.getId());

                // 将订单明细数据封装到VO中
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(o, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                orderVOList.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 查询订单详情
     * @param orderId
     * @return
     */
    @Override
    public OrderVO getOrderDetailById(Long orderId) {
        // 封装查询条件到orders对象
        Orders orders = new Orders();
        orders.setId(orderId);
        // 查询order数据
        List<Orders> ordersList = orderMapper.select(orders);
        // 判断是否获取到数据
        if (ordersList == null || ordersList.isEmpty()){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 查询orderDetail数据
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderId);
        // 封装到VO对象中
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(ordersList.get(0), orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 再来一单
     * @param orderId
     */
    @Override
    public void oneMoreOrder(Long orderId) {
        // 获取当前订单的数据
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderId);
        // 将数据插入到购物车
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            // 封装购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            // 插入购物车集合
            shoppingCartList.add(shoppingCart);
        }
        // 批量插入
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 用户订单取消
     * @param id
     */
    @Override
    public void cancelById(Long id) {
        // 封装查询条件
        Orders orders = new Orders();
        orders.setId(id);
        // 设置订单状态 -- 已取消
        orders.setStatus(Orders.CANCELLED);
        // 设置取消时间
        orders.setCancelTime(LocalDateTime.now());
        // 设置取消原因
        orders.setCancelReason("用户取消订单");
        orderMapper.update(orders);
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = Orders.builder().id(id).build();
        // 查询当前订单
        List<Orders> ordersList = orderMapper.select(orders);
        // 判断是否为空
        if (ordersList == null || ordersList.isEmpty()){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", ordersList.get(0).getId());
        map.put("content", "订单号：" + ordersList.get(0).getNumber());
        // 将数据转换为json格式发送给所有连接
        websocketServer.sendToAllClient(JSONUtils.toJSONString(map));
    }

    /**
     * 统计各状态订单数量
     * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
     * @return
     */
    @Override
    public OrderStatisticsVO getOrderStatusCount() {
        // 定义对象接收查询结果
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        // 查询待接单数量
        orderStatisticsVO.setToBeConfirmed(orderMapper.selectCountByStatus(Orders.TO_BE_CONFIRMED));
        // 查询待派送数量
        orderStatisticsVO.setConfirmed(orderMapper.selectCountByStatus(Orders.CONFIRMED));
        // 查询派送中数量
        orderStatisticsVO.setDeliveryInProgress(orderMapper.selectCountByStatus(Orders.DELIVERY_IN_PROGRESS));
        // 返回查询结果
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.update(Orders.builder().id(ordersConfirmDTO.getId()).status(Orders.CONFIRMED).build());
    }

    /**
     * 配送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        // 查询当前订单判断订单状态
        List<Orders> ordersDBList = orderMapper.select(Orders.builder().id(id).build());
        if (ordersDBList == null || ordersDBList.isEmpty()){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (!Objects.equals(ordersDBList.get(0).getStatus(), Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新订单状态
        orderMapper.update(Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build());
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void comolete(Long id) {
        // 查询当前订单,判断订单状态是否为配送中
        List<Orders> ordersDBList = orderMapper.select(Orders.builder().id(id).build());
        if (ordersDBList == null || ordersDBList.isEmpty()){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (!Objects.equals(ordersDBList.get(0).getStatus(), Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 完成订单
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒绝订单
     * @param ordersRejectionDTO
     */
    @Override
    @Transactional
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 获取当前订单的状态
        List<Orders> ordersDBList = orderMapper.select(Orders.builder().id(ordersRejectionDTO.getId()).build());
        // 判断是否为空
        if (ordersDBList == null || ordersDBList.isEmpty()){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Orders ordersDB = ordersDBList.get(0);
        // 判断当前订单是否处于待接单状态
        if (!Objects.equals(ordersDB.getStatus(), Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 封装数据
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();

        // 判断用户是否已经付款
        if (Objects.equals(ordersDBList.get(0).getPayStatus(), Orders.PAID)){
            // 为用户进行退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
            orders.setPayStatus(Orders.REFUND);
        }

        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    @Transactional
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 获取当前订单的状态
        List<Orders> ordersDBList = orderMapper.select(Orders.builder().id(ordersCancelDTO.getId()).build());
        // 判断是否为空
        if (ordersDBList == null || ordersDBList.isEmpty()){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Orders ordersDB = ordersDBList.get(0);

        // 封装数据
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();

        // 判断用户是否已经付款
        if (Objects.equals(ordersDBList.get(0).getPayStatus(), Orders.PAID)){
            // 为用户进行退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
            orders.setPayStatus(Orders.REFUND);
        }

        orderMapper.update(orders);
    }

    /**
     * 判断是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address){
        // 初始基础配置
        Map map = new HashMap();
        map.put("output", "json");
        map.put("ak", ak);
        // 设置商家地址
        map.put("address", shopAddress);
        // 调用getCoordinate方法,获取商家地址经纬度坐标
        String shopCoordinate = getCoordinate(map);

        // 设置用户地址
        map.put("address", address);
        // 调用getCoordinate方法,获取用户地址经纬度坐标
        String userCoordinate = getCoordinate(map);

        // 配置路线规划基础设置
        map.put("origin", shopCoordinate);
        map.put("destination", userCoordinate);
        map.put("step_info", "0");

        // 发送请求,进行路线规划
        String json = HttpClientUtil.doGet(BAIDU_DIRECTIONLITE_URL, map);
        // 解析json数据
        JSONObject jsonObject = JSON.parseObject(json);
        // 判断是否解析成功
        if (!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("地址解析失败");
        }
        // 获取路线规划结果
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = result.getJSONArray("routes");
        if (jsonArray.isEmpty()){
            throw new OrderBusinessException("地址解析失败");
        }
        // 获取距离
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
        if (distance > 5000){
            throw new OrderBusinessException("超出配送范围");
        }
    }

    /**
     * 获取地址经纬度坐标
     * @param map
     * @return
     */
    private String getCoordinate(Map map){
        // 发送请求，获取地址经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet(BAIDU_GEOCODING_URL, map);
        // 解析json数据
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        // 判断是否解析成功
        if (!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("地址解析失败");
        }
        // 获取经纬度 -- lng: 经度,  lat: 纬度
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lng = location.getString("lng");
        String lat = location.getString("lat");
        log.info("地址:{}的经纬度坐标:    {}",map.get("address"), lng + "," + lat);
        return lat + "," + lng;
    }
}
